package com.tjetc.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigUtil {
    private static final Properties properties = new Properties();
    private static final String CONFIG_FILE = "config.properties";
    private static boolean isLoaded = false;

    static {
        loadConfig();
    }

    private static void loadConfig() {
        try (InputStream input = ConfigUtil.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) {
            if (input == null) {
                LogUtil.warn("未找到配置文件: " + CONFIG_FILE + "，将使用默认配置");
                setDefaultConfig();
            } else {
                properties.load(input);
                LogUtil.info("成功加载配置文件");
            }
            isLoaded = true;
        } catch (IOException e) {
            LogUtil.error("加载配置文件失败", e);
            setDefaultConfig();
        }
    }

    private static void setDefaultConfig() {
        // 服务器配置
        properties.setProperty("server.host", "localhost");
        properties.setProperty("server.port", "8888");
        
        // 数据库配置
        properties.setProperty("db.url", "jdbc:mysql://localhost:3306/community");
        properties.setProperty("db.username", "root");
        properties.setProperty("db.password", "root");
        
        // 日志配置
        properties.setProperty("log.level", "INFO");
        properties.setProperty("log.dir", "logs");
        
        // 系统配置
        properties.setProperty("system.name", "社区管理系统");
        properties.setProperty("system.version", "1.0.0");
        
        // 重试配置
        properties.setProperty("retry.maxAttempts", "3");
        properties.setProperty("retry.delay", "1000");
    }

    public static String getProperty(String key) {
        if (!isLoaded) {
            loadConfig();
        }
        return properties.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if (!isLoaded) {
            loadConfig();
        }
        return properties.getProperty(key, defaultValue);
    }

    public static int getIntProperty(String key, int defaultValue) {
        String value = getProperty(key);
        if (value == null) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            LogUtil.warn("配置项 " + key + " 的值不是有效的整数: " + value);
            return defaultValue;
        }
    }

    public static boolean getBooleanProperty(String key, boolean defaultValue) {
        String value = getProperty(key);
        if (value == null) {
            return defaultValue;
        }
        return Boolean.parseBoolean(value);
    }

    public static void reload() {
        isLoaded = false;
        loadConfig();
    }
} 